<?php

declare(strict_types=1);

namespace App\Middleware;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Qbhy\HyperfAuth\AuthManager;

class AuthMiddleware implements MiddlewareInterface
{
    protected AuthManager $auth;
    protected ContainerInterface $container;

    protected RequestInterface $request;

    protected HttpResponse $response;

    protected $allowUri = [
        '/kpi/passport/login',
        '/kpi/passport/logout',
        '/kpi/passport/captcha',
    ];

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request, AuthManager $auth)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;

        $this->auth = $auth;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 获取当前请求uri，判断是否需要授权访问
        if ($this->request->is('kpi/*')){
            // 后台接口访问需要授权
            $uri = $this->request->getPathInfo();
            if (!in_array($uri, $this->allowUri)) {
                $isValidToken = $this->auth->guard('jwt')->check();
                if (!$isValidToken) {
                    return $this->response->json(
                        [
                            'code' => 401,
                            'message' => '认证失败请重新登录',
                            'data' => null
                        ]
                    );
                }
            }
        }

        return $handler->handle($request);
    }
}